package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.DeviceBo;
import org.dromara.system.domain.bo.ResponsibleDeviceBo;
import org.dromara.system.domain.bo.SensorBo;
import org.dromara.system.domain.dto.AlarmDeviceDto;
import org.dromara.system.domain.pojo.DeviceOverview;
import org.dromara.system.domain.protocol.FaultCodeTranslator;
import org.dromara.system.domain.protocol.ProtocolParsing;
import org.dromara.system.domain.vo.*;
import org.dromara.system.mapper.*;
import org.dromara.system.service.IDeviceGroupService;
import org.dromara.system.service.IDeviceService;
import org.dromara.system.service.ISensorService;
import org.dromara.system.service.ISysSystemService;
import org.dromara.system.utils.CalculatorUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 *
 * @author Lion Li
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class DeviceServiceImpl implements IDeviceService {

    private final DeviceMapper baseMapper;

    private final DeviceGroupMapper deviceGroupMapper;

    private final DeviceAlarmMapper deviceAlarmMapper;


    private final DeviceVariableAssociationMapper deviceVariableAssociationMapper;

    private final ISensorService sensorService;

    private final DeviceUserGroupMapper deviceUserGroupMapper;

    private final VariableAssociationMapper variableAssociationMapper;

    private final DeviceCollectMapper deviceCollectMapper;

    private final ISysSystemService systemService;

    private final IDeviceGroupService deviceGroupService;

    private final SysUserRoleMapper userRoleMapper;


    /**
     * 分页查询设备信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 设备信息分页列表
     */
    @Override
    public TableDataInfo<DeviceVo> queryPageList(DeviceBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();

        LambdaQueryWrapper<Device> lqw = buildQueryWrapper(bo);
        Page<DeviceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (result.getRecords().isEmpty()) return TableDataInfo.build(result);
        result.getRecords().forEach(deviceVo -> {
            deviceVo.setGroupName(deviceGroupMapper.getGroupNameById(deviceVo.getGroupId()));
            int alarm = deviceAlarmMapper.getAlarm(deviceVo.getId());
            deviceVo.setAlarm(alarm == 0 ? 0 : 1);
            deviceVo.setCollect(deviceCollectMapper.selectCollect(userId, deviceVo.getId()));
            List<Long> variableAssociations = deviceVariableAssociationMapper.selectVariableAssociationIds(deviceVo.getId());
            if (variableAssociations.isEmpty()) deviceVo.setVariableAssociationIds(new ArrayList<>());
            deviceVo.setVariableAssociationIds(variableAssociations);
            deviceVo.setVariableList(baseMapper.getDeviceVariableValueList(deviceVo.getId()));
            deviceVo.setTunnelName(getTunnelName(deviceVo.getTunnelId()));
        });
        return TableDataInfo.build(result);
    }

    private String getTunnelName(Long tunnelId) {
        Map<Long, String> tunnelMap = new HashMap<>();
        tunnelMap.put(1L,"应天大街隧道");
        tunnelMap.put( 2L,"定淮门隧道");
        tunnelMap.put(3L,"江心洲大桥");
        return tunnelMap.get(tunnelId);
    }

    /**
     * 查询符合条件的设备信息列表
     *
     * @param bo 查询条件
     * @return 设备信息列表
     */
    @Override
    public List<DeviceVo> queryList(DeviceBo bo) {
        LambdaQueryWrapper<Device> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Device> buildQueryWrapper(DeviceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Device> lqw = Wrappers.lambdaQuery();
        if (bo.getGroupId() != null) {
            String[] groupIdArray = bo.getGroupId().split(",");
            List<Long> groupIdList = new ArrayList<>();
            for (String id : groupIdArray) {
                try {
                    groupIdList.add(Long.parseLong(id.trim()));
                } catch (NumberFormatException e) {
                    // 处理非法的数字格式，可以选择忽略或抛出异常
                    continue;
                }
            }
            lqw.in(!groupIdList.isEmpty(), Device::getGroupId, groupIdList);
        }else{
            Long userId = LoginHelper.getUserId();
            Long roleId = userRoleMapper.getRoleId(userId);
            if (roleId != 1L){
                List<Long> longs = deviceUserGroupMapper.selectGroupIdListByUserId(userId);
                if (!longs.isEmpty()){
                    lqw.in(Device::getGroupId, longs);
                }else {
                    lqw.eq(Device::getId, 0L);
                }
            }
        }
            lqw.eq(StringUtils.isNotBlank(bo.getDeviceNo()), Device::getDeviceNo, bo.getDeviceNo());
        lqw.like(StringUtils.isNotBlank(bo.getDeviceName()), Device::getDeviceName, bo.getDeviceName());
        lqw.eq(bo.getStatus() != null, Device::getStatus, bo.getStatus());
        lqw.eq(bo.getCollect() != null, Device::getCollect, bo.getCollect());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), Device::getAddress, bo.getAddress());
        return lqw;
    }

    /**
     * 新增设备信息
     *
     * @param bo 设备信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(DeviceBo bo) {
        bo.setDeviceNo(UUID.randomUUID().toString());
        Device add = MapstructUtils.convert(bo, Device.class);
        validEntityBeforeSave(add);

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            Long deviceId = add.getId();
            bo.setId(deviceId);
            baseMapper.deleteVariableAssociation(bo.getId());
            setVariableAssociation(bo.getId(), List.of(bo.getVariableAssociation()));
        }

        return flag;
    }


    /**
     * 修改设备信息
     *
     * @param bo 设备信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(DeviceBo bo) {
        Device update = MapstructUtils.convert(bo, Device.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            baseMapper.deleteVariableAssociation(bo.getId());
            setVariableAssociation(bo.getId(), List.of(bo.getVariableAssociation()));
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Device entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除设备信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public DeviceInfoVo getDeviceInfoById(Long id) {
        DeviceVo deviceVo = baseMapper.selectVoById(id);
        DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
        deviceInfoVo.setDeviceNo(deviceVo.getDeviceNo());
        deviceInfoVo.setDeviceName(deviceVo.getDeviceName());
        deviceInfoVo.setGroupId(deviceVo.getGroupId());
        deviceInfoVo.setGroupName(deviceGroupMapper.getGroupNameById(deviceVo.getGroupId()));
        deviceInfoVo.setVariableAssociation(deviceVo.getVariableAssociation());
        deviceInfoVo.setStatus(deviceVo.getStatus());
        deviceInfoVo.setAddress(deviceVo.getAddress());
        deviceInfoVo.setSite(deviceVo.getSite());

        int alarm = deviceAlarmMapper.getAlarm(deviceVo.getId());
        deviceVo.setAlarm(alarm == 0 ? 0 : 1);
        deviceInfoVo.setRemark(deviceVo.getRemark());
        deviceInfoVo.setId(deviceVo.getId());

        List<VariableAssociationDescVo> variableAssociations = baseMapper.selectVariableAssociationList(id);
        processVariableAssociations(variableAssociations);
        deviceInfoVo.setVariableAssociationList(variableAssociations);

        if (deviceVo.getGroupId() == 0) {
            deviceInfoVo.setChannelId(2L);
        } else {
            deviceInfoVo.setChannelId(deviceGroupService.getRootNodeId(deviceVo.getGroupId()));
        }

        return deviceInfoVo;
    }

    private void processVariableAssociations(List<VariableAssociationDescVo> variableAssociations) {
        for (VariableAssociationDescVo variableAssociation : variableAssociations) {
            if (variableAssociation.getValueDescJson() == null) {
                variableAssociation.setValueText(new ArrayList<>());
                variableAssociation.setValueDesc("");
            } else {
                List<VariableAssociationValueDescVo> variableAssociationValueDescVo = JsonUtils.parseArray(variableAssociation.getValueDescJson(), VariableAssociationValueDescVo.class);
                variableAssociation.setValueText(variableAssociationValueDescVo);
                variableAssociation.setValueDesc(getTextByValue(variableAssociationValueDescVo, variableAssociation.getValue()));
            }
        }
    }

    private String getTextByValue(List<VariableAssociationValueDescVo> valueDescList, BigDecimal value) {
        for (VariableAssociationValueDescVo vo : valueDescList) {
            if (vo.getValue().compareTo(value) == 0) {
                return vo.getText();
            }
        }
        return null; // 如果没有找到匹配的值，返回null或其他默认值
    }




    @Override
    public DashVo dashBroad() {
        DashVo dashVo = new DashVo();
        dashVo.setTunnelCount(3L);

        // 获取设备总数
        Long deviceCount = baseMapper.selectCount(new LambdaQueryWrapper<>());
        // 获取报警总数
        Long alarmCount = deviceAlarmMapper.selectAlarmCount();

        // 设置设备相关数据
        dashVo.setDeviceCount(deviceCount);
        Long normalDeviceCount = Math.max(0L, deviceCount - alarmCount);
        dashVo.setNormalDeviceCount(normalDeviceCount);
        dashVo.setAbnormalDeviceCount(baseMapper.selectCount(new LambdaQueryWrapper<Device>().eq(Device::getStatus, 1)));
        // 获取已处理报警数
        Long alarmHandleCount = deviceAlarmMapper.selectCount(new LambdaQueryWrapper<DeviceAlarm>().eq(DeviceAlarm::getStatus, 1));

        // 设置报警相关数据
        dashVo.setAlarmCount(alarmCount);
        dashVo.setAlarmALLCount(deviceAlarmMapper.selectAllCount());
        dashVo.setAlarmHandleCount(alarmHandleCount);
        dashVo.setAlarmUnprocessedCount(deviceAlarmMapper.selectAlarmCount());

        return dashVo;
    }


    @Override
    public int setVariableAssociation(Long deviceId, Collection<Long> ids) {
        int bs = baseMapper.deleteVariableAssociation(deviceId);
        int rs = baseMapper.setVariableAssociation(deviceId, ids);
        return bs + rs;
    }

    @Override
    public int unbindDeviceVariable(Long deviceId, Long id) {
        return baseMapper.unbindVariableAssociation(deviceId, id);
    }

    @Override
    public int bindDeviceVariable(Long deviceId, Long id) {
        return baseMapper.bindDeviceVariable(deviceId, id);
    }

    @Override
    public List<SensorVo> getDeviceVariableValueList(Long id) {
        List<SensorVo> sensorVoList = sensorService.selectSensorList(id);
//        sensorVoList.forEach(sensorVo -> {
//            sensorVo.setTs(CalculatorUtils.convertUtcToChinaTimeWithFormat(sensorVo.getTs()));
//        });
        return sensorService.selectSensorList(id);
    }

    @Override
    public StatisticsVo statistics(Long userId) {
        Long alarmCount =  deviceAlarmMapper.selectAlarmCount();
        StatisticsVo statisticsVo = new StatisticsVo();
        statisticsVo.setAlarmCount(Math.toIntExact(alarmCount));
        statisticsVo.setDataSourceCount(0);
        return statisticsVo;
    }

    @Override
    public TableDataInfo<DeviceNameVo> getDeviceVariableList(String ids, PageQuery pageQuery) {
        List<Long> longs = CalculatorUtils.convertToLongList(ids);
        LambdaQueryWrapper<Device> lqw = Wrappers.lambdaQuery();
        if (!longs.isEmpty()) {
            lqw.in(Device::getGroupId, longs);
        }
        Page<DeviceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        // 创建一个新的 Page 对象
        Page<DeviceNameVo> deviceNameVoPage = new Page<>();
        deviceNameVoPage.setTotal(result.getTotal());

        // 手动转换记录
        List<DeviceNameVo> deviceNameVoList = result.getRecords().stream()
                .map(this::convertToDeviceNameVo)
                .collect(Collectors.toList());

        deviceNameVoPage.setRecords(deviceNameVoList);
        if (!deviceNameVoPage.getRecords().isEmpty()) {
            for (DeviceNameVo record : deviceNameVoPage.getRecords()) {
                List<NameVo> variableList = baseMapper.getDeviceVariableValueList(record.getId());
                record.setVariableList(variableList);
            }
        }
        return TableDataInfo.build(deviceNameVoPage);
    }

    @Override
    public TableDataInfo<HistoryVo> getHistoryList(SensorBo bo, PageQuery pageQuery) {
        IPage<SensorVo> result = sensorService.getPagedDataByDeviceId(bo.getVariableId(), pageQuery, bo.getStartTime(), bo.getEndTime());
        System.out.println(result.getRecords());
        IPage<HistoryVo> deviceNameVoPage = new Page<>();
        deviceNameVoPage.setTotal(result.getTotal());

        List<HistoryVo> deviceNameVoList = result.getRecords().stream()
            .map(this::convertHistoryVo)
            .collect(Collectors.toList());
        deviceNameVoPage.setRecords(deviceNameVoList);
        VariableAssociation variableAssociation= variableAssociationMapper.selectById(bo.getVariableId());
        if (!deviceNameVoPage.getRecords().isEmpty()) {
            for (HistoryVo record : deviceNameVoPage.getRecords()) {
                if (variableAssociation != null) {
                    record.setName(variableAssociation.getAlias());
                    record.setUnity(variableAssociation.getUnity());
                    record.setVariableId(bo.getVariableId());
//                    record.setTs(CalculatorUtils.convertUtcToChinaTimeWithFormat(record.getTs()));
                    if (variableAssociation.getValueDescJson() == null) {
                        record.setValueDescJson("");
                        record.setValueText(new ArrayList<>());
                        record.setValueDesc("");
                    } else {
                        List<VariableAssociationValueDescVo> valueDescList = JsonUtils.parseArray(variableAssociation.getValueDescJson(), VariableAssociationValueDescVo.class);
                        record.setValueDescJson(variableAssociation.getValueDescJson());
                        record.setValueText(valueDescList);
                        record.setValueDesc(getTextByValue(valueDescList, record.getValue()));
                    }
                } else {
                    // 设置默认值或其他处理逻辑
                    record.setName("");
                    record.setUnity("");
                    record.setValueDescJson(null);
                    record.setValueText(new ArrayList<>());
                    record.setValueDesc("");
                }
            }
        }

        return TableDataInfo.build(deviceNameVoPage);
    }


    @Override
    public TableDataInfo<DeviceCollectListVo> getResponsibleDevice(ResponsibleDeviceBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        Integer page = getPageNumber(pageQuery.getPageNum());
        Integer pageSize = getPageSize(pageQuery.getPageSize());
        Page<DeviceCollectListVo> pages = new Page<>(page, pageSize);

        List<Long> groupIdList = parseGroupIds(bo.getGroupId());

        IPage<DeviceCollectListVo> result = deviceCollectMapper.queryPageList(pages, groupIdList, bo.getDeviceName(), userId);
        return TableDataInfo.build(result);
    }

    @Override
    public List<SysSystem> getDataSource() {
        return systemService.getDataSource();
//        return SystemUtils.getSystemInfo();
    }

    @Override
    public void insertUdpDevice(ProtocolParsing sensorData) {
        //根据分机编号和分机桩号查询设备表
        Device device = baseMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getDeviceNo, sensorData.getExtensionNumber()).eq(Device::getPileNumber, sensorData.getExtensionPileNumber()));
        if (device == null) {
            //插入设备表
            Device devices = new Device();
            devices.setDeviceNo(sensorData.getExtensionNumber());
            devices.setGroupId(82L);
            devices.setPileNumber(sensorData.getExtensionPileNumber());
            devices.setDeviceName(sensorData.getExtensionName());
            devices.setDeviceType(sensorData.getExtensionType() + 1);
            devices.setStatus(1);
            devices.setCreateTime(sensorData.getTimestamp());
            devices.setCreateBy(1L);
            baseMapper.insert(devices);
        } else {
            device.setUpdateTime(sensorData.getTimestamp());
            device.setUpdateBy(1L);
            baseMapper.updateById(device);
        }
        //插入设备报警表
        if (sensorData.getControlCommand().equals("A") && !Objects.equals(sensorData.getMessageData(), "0")) {
            DeviceAlarm deviceAlarm = new DeviceAlarm();
            deviceAlarm.setDeviceId(device.getId());
            deviceAlarm.setDeviceName(device.getDeviceName());
            deviceAlarm.setDeviceGroup(82L);
            deviceAlarm.setVariableId(0L);
            deviceAlarm.setVariableName("");
            deviceAlarm.setContent(FaultCodeTranslator.getFaultDescription(sensorData.getMessageData()));
            deviceAlarm.setAlarmValue(sensorData.getMessageData());
            deviceAlarm.setLevel(1L);
            deviceAlarmMapper.insert(deviceAlarm);
        }

        //插入到变量表
        VariableAssociation variableAssociation = variableAssociationMapper.findPhoneByNumber(sensorData.getExtensionNumber(), sensorData.getExtensionPileNumber());

        if (variableAssociation == null) {
            VariableAssociation deviceAssociation = new VariableAssociation();
            deviceAssociation.setAlias(sensorData.getExtensionName());
            deviceAssociation.setName(sensorData.getExtensionName());
            deviceAssociation.setCode(sensorData.getExtensionNumber());
            deviceAssociation.setDescription("电话");
            deviceAssociation.setGroupId(4L);
            deviceAssociation.setIdentifier(0L);
            deviceAssociation.setMultiple(1L);
            deviceAssociation.setSlaveId(0);
            deviceAssociation.setSortNum(0L);
            deviceAssociation.setStatus(1);
            deviceAssociation.setUnity("");
            deviceAssociation.setPileNumber(sensorData.getExtensionPileNumber());
            deviceAssociation.setVariableType((long) (sensorData.getExtensionType() + 3));
            // 插入新记录
            variableAssociation.setSource(3);
            variableAssociationMapper.insert(deviceAssociation);
        }


    }

    @Override
    public List<StatisticsDeviceVo> getDeviceChart(Long id) {
        // 获取总设备数量
        Integer total = baseMapper.selectTotalCount();

        // 获取所有子节点
        List<StatisticsDeviceVo> subGroupsByParentId = deviceGroupMapper.findSubGroupsByParentId(id);

        // 缓存每个子节点及其所有子节点的ID
        Map<Long, List<Long>> subNodeCache = new HashMap<>();
        for (StatisticsDeviceVo statisticsDeviceVo : subGroupsByParentId) {
            Long groupId = statisticsDeviceVo.getId();
            if (!subNodeCache.containsKey(groupId)) {
                subNodeCache.put(groupId, deviceGroupMapper.findAllSubNodeIds(groupId));
            }
        }

        // 批量查询所有有设备的组ID
//        List<Long> groupIdsWithDevices = baseMapper.selectGroupIdsWithDevices();

        // 计算每个子节点的设备数量和比例
        for (StatisticsDeviceVo statisticsDeviceVo : subGroupsByParentId) {
            Long groupId = statisticsDeviceVo.getId();
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<Device>().eq(Device::getGroupId, groupId));

            List<Long> subNodeIds = subNodeCache.get(groupId);
            Long subNodeCount = 0L;
            if (subNodeIds != null && !subNodeIds.isEmpty()) {
                subNodeCount = baseMapper.selectCount(new LambdaQueryWrapper<Device>().in(Device::getGroupId, subNodeIds));
            }

            statisticsDeviceVo.setCount(count + subNodeCount);
            statisticsDeviceVo.setRatio(BigDecimal.valueOf(statisticsDeviceVo.getCount()).divide(BigDecimal.valueOf(total), 2, RoundingMode.HALF_UP));
        }

        return subGroupsByParentId;
    }

    @Override
    public List<DeviceOverview> deviceOverview() {

        List<DeviceOverview> deviceOverviews = new ArrayList<>();
        Long normalDeviceCount = 0L;
        //TODO 后续优化成数据库查询方式
        for (int i = 0; i < 3; i++) {
            Long total = baseMapper.selectCount(new LambdaQueryWrapper<Device>().eq(Device::getTunnelId, i + 1));
            DeviceOverview deviceOverview = new DeviceOverview();
            deviceOverview.setTunnelId((long) (i + 1));
            deviceOverview.setTunnelName(deviceGroupMapper.getGroupNameById((long) (i + 1)));
            normalDeviceCount = baseMapper.selectCount(new LambdaQueryWrapper<Device>().ne(Device::getStatus, 2).eq(Device::getTunnelId, i + 1));
            deviceOverview.setNormalDeviceCount(normalDeviceCount);
            deviceOverview.setAlarmDeviceCount(deviceAlarmMapper.selectAlarmDeviceCount(i + 1));
            if (total == 0) {
                deviceOverview.setNormalRate(BigDecimal.ZERO);
            } else {
                deviceOverview.setNormalRate(BigDecimal.valueOf(normalDeviceCount).divide(BigDecimal.valueOf(total), 2, RoundingMode.DOWN));
            }
            deviceOverviews.add(deviceOverview);
        }
        return deviceOverviews;
    }

    @Override
    public List<DeviceGroupVo> liquidLevelGauge() {
        //根据节点id获取当前节点的父节点 如果父节点患有父节点 则继续 一直到根节点
        List<Long> selectedIds = List.of(98L, 18L, 6L);
        List<DeviceGroupVo> allNodes = deviceGroupMapper.selectVoList();
        Map<Long, DeviceGroupVo> idToNodeMap = allNodes.stream()
                .collect(Collectors.toMap(DeviceGroupVo::getId, node -> node));
        // 从目标节点集合向上追溯到顶级节点
        List<DeviceGroupVo> topNodes = traceToTopNodes(selectedIds, idToNodeMap);
        for (DeviceGroupVo deviceGroupVo : topNodes) {
            List<Long> allSubNodeIds = deviceGroupMapper.findAllSubNodeIds(deviceGroupVo.getId());
            //判断deviceGroupVo.getId() 在selectedIds这个集合里面
            Long count;
            if (selectedIds.contains(deviceGroupVo.getId())) {
                count = baseMapper.selectCount(new LambdaQueryWrapper<Device>().in(Device::getGroupId, deviceGroupVo.getId()));
            } else {
                count = baseMapper.selectCount(new LambdaQueryWrapper<Device>().in(Device::getGroupId, allSubNodeIds));
            }
            deviceGroupVo.setCount(count != null ? count : 0L);
        }
        return buildTree(topNodes, idToNodeMap);
    }



    private List<DeviceGroupVo> traceToTopNodes(List<Long> selectedIds, Map<Long, DeviceGroupVo> idToNodeMap) {
        List<DeviceGroupVo> relatedNodes = new ArrayList<>();
        for (Long selectedId : selectedIds) {
            DeviceGroupVo currentNode = idToNodeMap.get(selectedId);
            if (currentNode == null) {
                continue;
            }
            while (currentNode != null) {
                if (!relatedNodes.contains(currentNode)) {
                    relatedNodes.add(currentNode);
                }
                if (currentNode.getParentId() == null) {
                    break;
                }
                currentNode = idToNodeMap.get(currentNode.getParentId());
            }
        }
        return relatedNodes;
    }


    private List<DeviceGroupVo> buildTree(List<DeviceGroupVo> nodes, Map<Long, DeviceGroupVo> idToNodeMap) {
        Map<Long, DeviceGroupVo> nodeMap = new HashMap<>();
        for (DeviceGroupVo node : nodes) {
            nodeMap.put(node.getId(), node);
        }

        List<DeviceGroupVo> roots = new ArrayList<>();
        for (DeviceGroupVo node : nodes) {
            if (node.getParentId() == null || !nodeMap.containsKey(node.getParentId())) {
                roots.add(node);
            } else {
                DeviceGroupVo parent = nodeMap.get(node.getParentId());
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(node);
            }
        }
        return roots;
    }


    private Integer getPageNumber(Integer pageNum) {
        return pageNum == null ? 1 : pageNum;
    }

    private Integer getPageSize(Integer pageSize) {
        return pageSize == null ? 20 : pageSize;
    }

    private List<Long> parseGroupIds(String groupIdStr) {
        List<Long> groupIdList = new ArrayList<>();
        if (groupIdStr != null) {
            String[] groupIdArray = groupIdStr.split(",");
            for (String id : groupIdArray) {
                try {
                    groupIdList.add(Long.parseLong(id.trim()));
                } catch (NumberFormatException e) {
                    // 记录日志或抛出更具体的异常
                    continue;
                }
            }
        }
        return groupIdList;
    }


//    private HistoryVo convertHistoryVo(SensorVo sensorVo) {
//        VariableAssociation variableAssociation = variableAssociationMapper.selectById(sensorVo.getDeviceId());
//        HistoryVo historyVo = new HistoryVo();
//        historyVo.setTs(sensorVo.getTs());
//        BigDecimal value=CalculatorUtils.processScientificNotation(sensorVo.getValue());
//        historyVo.setValue(value);
//        historyVo.setName(variableAssociation.getAlias());
//        historyVo.setUnity(variableAssociation.getUnity());
//        historyVo.setVariableId(variableAssociation.getId());
//        if (variableAssociation.getValueDescJson() == null) {
//            historyVo.setValueDescJson(null);
//            historyVo.setValueText(new ArrayList<>());
//            historyVo.setValueDesc("");
//        } else {
//            List<VariableAssociationValueDescVo> variableAssociationValueDescVo = JsonUtils.parseArray(variableAssociation.getValueDescJson(), VariableAssociationValueDescVo.class);
//            historyVo.setValueDescJson(variableAssociation.getValueDescJson());
//            historyVo.setValueText(variableAssociationValueDescVo);
//            historyVo.setValueDesc(getTextByValue(variableAssociationValueDescVo, value));
//        }
//        // 设置其他需要的字段
//        return historyVo;
//    }

    private HistoryVo convertHistoryVo(SensorVo sensorVo) {
        HistoryVo historyVo = new HistoryVo();
        historyVo.setTs(sensorVo.getTs());
        historyVo.setValue(CalculatorUtils.processScientificNotation(sensorVo.getValue()));
        historyVo.setVariableId(sensorVo.getDeviceId());
        // 设置其他需要的字段
        return historyVo;
    }


    private DeviceNameVo convertToDeviceNameVo(DeviceVo deviceVo) {
        DeviceNameVo deviceNameVo = new DeviceNameVo();
        deviceNameVo.setId(deviceVo.getId());
        deviceNameVo.setDeviceName(deviceVo.getDeviceName());
        // 设置其他需要的字段
        return deviceNameVo;
    }

    private Integer getAlarmCount(Long userId) {
        List<Long> deviceIds = deviceUserGroupMapper.selectGroupIdListByUserId(userId);
        return deviceAlarmMapper.getAlarmCountByIds(deviceIds);
    }

    private List<AlarmDeviceDto> getDeviceList(Long userId) {
        List<Long> deviceIds = deviceUserGroupMapper.selectGroupIdListByUserId(userId);
        return deviceAlarmMapper.getAlarmDeviceListByIds(deviceIds);
    }


}
